package com.hmdp.config;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.PostConstruct;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class RabbitMqConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    private final RabbitTemplate rabbitTemplate;

    private final StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void init() {
        // 在 RabbitTemplate 初始化后设置 ConfirmCallback
        rabbitTemplate.setConfirmCallback(this);
        // 设置 ReturnCallback
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String msgId = correlationData != null ? correlationData.getId() : "";
        if (StrUtil.isBlank(msgId)) {
            return;
        }
        if (ack) {
            log.info("消息ID：{}成功发送到Broker。", msgId);
        } else {
            log.error("消息ID：{}发送失败，原因：{}", msgId, cause);
            // TODO 重试机制
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.error("消息从 Exchange 发送到 Queue 失败！");
        log.error("消息内容: {}", new String(message.getBody()));
        log.error("返回码: {}", replyCode);
        log.error("返回文本: {}", replyText);
        log.error("交换机: {}", exchange);
        log.error("路由键: {}", routingKey);
        // TODO 这里通常需要记录日志、告警，或者将消息重新发送到备用队列进行处理
    }
}
